package com.example.naodian.websocket;

import com.example.naodian.service.IScheduledTasksService;
import com.example.naodian.service.impl.ScheduledTasksServiceImpl;
import com.example.naodian.task.MyTask;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
//    private MyTask myTask; // 假设 MyTask 是一个已定义的类
//
//    public WebSocketServer() {
//        // 初始化 myTask
//        this.myTask = new MyTask();
//    }

    // 用于存储所有连接的客户端
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);  // 加入set中
        System.out.println("有新连接加入！当前在线人数为" + webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // 从set中删除
        System.out.println("有一连接关闭！当前在线人数为" + webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("来自客户端的消息:" + message);
        // 可以在这里处理接收到的消息
        // 处理业务逻辑
//        if (message.equals("start")){
//            myTask.startTask();
//        }else {
//            myTask.stopTask();
//        }
    }
    private String processData(String data) {
        // 实现你的业务逻辑
        return "处理后的数据: " + data.toUpperCase();
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        if (this.session == null) {
            System.err.println("Session 为空，无法发送消息");
            return;
        }
        this.session.getBasicRemote().sendText(message);
    }

    public static void broadcast(String message) {
        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.session != null) { // 过滤掉 session 为 null 的实例
                    item.sendMessage(message);
                } else {
                    System.err.println("跳过 session 为空的实例");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
